#去掉通过推广链接访问说店铺不存在的链接
#TODO 现只是把其prom_url的值改为'bad'

require File.expand_path('../../config/environment',  __FILE__)
require 'thread'

#Rails.logger = Logger.new $stdout

task_queue = Queue.new
empty_count = 0
last_id = 15534 #FIXME 记得改回为0

browser_queue = Queue.new
1.times do
  browser_queue << (Watir::Browser.new :firefox, :profile => 'default')
end

thread_num = 1
threads = []
Thread.abort_on_exception = true
thread_num.times.each do
  threads << Thread.new do
    while true
      agent = Thread.current[:agent]
      if agent.nil?
        agent = browser_queue.pop
        Thread.current[:agent] = agent
      end
      begin
        if task_queue.empty?
          sleep thread_num * 1
          next
        end
        shop = task_queue.pop
        if shop
          result = agent.goto(shop.prom_url)
          case result
          when /noshop/
            shop.prom_url = 'bad'
            shop.save!
          when /view_shop/
            next
          else
            Rails.logger.warn "解析结果出错 #{shop.id} -- #{result}"
          end
        end
      rescue ThreadError => e
        Rails.logger.info "线程任务完成 #{Thread.current.object_id} , #{e.message}"
        break
      rescue Exception => e
        driver = agent.driver
        bridge = driver.instance_variable_get :@bridge
        launcher = bridge.instance_variable_get :@launcher
        binary = launcher.instance_variable_get :@binary
        process = binary.instance_variable_get :@process
        %x(kill -9 #{process.pid}) #直接kill掉进程
        Thread.current[:agent] = Watir::Browser.new :firefox, :profile => 'default'
        task_queue << shop
        Rails.logger.warn "验证推广链接出错, #{shop.id}, #{e.message}, #{e.backtrace.join "\n"}"
      end
    end
  end
end

while true
  if task_queue.size > 5
    sleep thread_num * 3
    next
  end

  shop_tasks = Shop.all(:conditions => "id > #{last_id} and prom_url is not null and prom_url <> 'bad'", :order => 'id ASC', :limit => 100)
  if shop_tasks.empty?
    empty_count += 1
    exit if empty_count > 5
    sleep 20*empty_count
    next
  else
    empty_count = 0
    last_id = shop_tasks.last.id
    shop_tasks.each{|shop_task| task_queue << shop_task}
    sleep thread_num * 3
  end
end
